<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="format-detection" content="telephone=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="icon" href="/images/icons/favicon-16x16.png?v=2.6.2" type="image/png" sizes="16x16"><link rel="icon" href="/images/icons/favicon-32x32.png?v=2.6.2" type="image/png" sizes="32x32"><meta name="description" content="–本文参考书籍： &amp;emsp;&amp;emsp;&amp;emsp;&amp;emsp;&amp;emsp;&amp;emsp;&amp;emsp; Stephen Prata的《C Primer Plus》">
<meta property="og:type" content="article">
<meta property="og:title" content="初识C语言">
<meta property="og:url" content="https://kohler19.gitee.io/2022/01/19/%E5%88%9D%E8%AF%86C%E8%AF%AD%E8%A8%80/index.html">
<meta property="og:site_name" content="愷龍的网络日志">
<meta property="og:description" content="–本文参考书籍： &amp;emsp;&amp;emsp;&amp;emsp;&amp;emsp;&amp;emsp;&amp;emsp;&amp;emsp; Stephen Prata的《C Primer Plus》">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s4.ax1x.com/2022/01/18/70YL7D.png">
<meta property="og:image" content="https://s4.ax1x.com/2022/01/03/Tb8ZB4.png">
<meta property="article:published_time" content="2022-01-19T05:59:07.000Z">
<meta property="article:modified_time" content="2022-01-22T05:27:12.113Z">
<meta property="article:author" content="李恺龙">
<meta property="article:tag" content="C语言">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s4.ax1x.com/2022/01/18/70YL7D.png"><title>初识C语言 | 愷龍的网络日志</title><link ref="canonical" href="https://kohler19.gitee.io/2022/01/19/%E5%88%9D%E8%AF%86C%E8%AF%AD%E8%A8%80/"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.12.1/css/all.min.css" type="text/css"><link rel="stylesheet" href="/css/index.css?v=2.6.2"><script>var Stun = window.Stun || {};
var CONFIG = {
  root: '/',
  algolia: undefined,
  assistSearch: undefined,
  fontIcon: {"prompt":{"success":"fas fa-check-circle","info":"fas fa-arrow-circle-right","warning":"fas fa-exclamation-circle","error":"fas fa-times-circle"},"copyBtn":"fas fa-copy"},
  sidebar: {"offsetTop":"20px","tocMaxDepth":6},
  header: {"enable":true,"showOnPost":true,"scrollDownIcon":false},
  postWidget: {"endText":true},
  nightMode: {"enable":true},
  back2top: {"enable":true},
  codeblock: {"style":"default","highlight":"light","wordWrap":false},
  reward: false,
  fancybox: false,
  zoomImage: {"gapAside":"20px"},
  galleryWaterfall: undefined,
  lazyload: false,
  pjax: undefined,
  externalLink: {"icon":{"enable":true,"name":"fas fa-external-link-alt"}},
  shortcuts: undefined,
  prompt: {"copyButton":"复制","copySuccess":"复制成功","copyError":"复制失败"},
  sourcePath: {"js":"js","css":"css","images":"images"},
};

window.CONFIG = CONFIG;</script><meta name="generator" content="Hexo 5.4.0"></head><body><div class="container" id="container"><header class="header" id="header"><div class="header-inner"><nav class="header-nav header-nav--fixed"><div class="header-nav-inner"><div class="header-nav-menubtn"><i class="fas fa-bars"></i></div><div class="header-nav-menu"><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/"><span class="header-nav-menu-item__icon"><i class="fas fa-home"></i></span><span class="header-nav-menu-item__text">首页</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/archives/"><span class="header-nav-menu-item__icon"><i class="fas fa-folder-open"></i></span><span class="header-nav-menu-item__text">归档</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/分类/"><span class="header-nav-menu-item__icon"><i class="fas fa-layer-group"></i></span><span class="header-nav-menu-item__text">分类</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/标签/"><span class="header-nav-menu-item__icon"><i class="fas fa-tags"></i></span><span class="header-nav-menu-item__text">标签</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/categories/Book/"><span class="header-nav-menu-item__icon"><i class="fas fa-book"></i></span><span class="header-nav-menu-item__text">书籍</span></a></div></div><div class="header-nav-search"><span class="header-nav-search__icon"><i class="fas fa-search"></i></span><span class="header-nav-search__text">搜索</span></div><div class="header-nav-mode"><div class="mode"><div class="mode-track"><span class="mode-track-moon"></span><span class="mode-track-sun"></span></div><div class="mode-thumb"></div></div></div></div></nav><div class="header-banner"><div class="header-banner-info"><div class="header-banner-info__title">愷龍的网络日志</div><div class="header-banner-info__subtitle">每天多学一点，以后就少敲一点代码</div></div></div></div></header><main class="main" id="main"><div class="main-inner"><div class="content-wrap" id="content-wrap"><div class="content" id="content"><!-- Just used to judge whether it is an article page--><div id="is-post"></div><div class="post"><header class="post-header"><h1 class="post-title">初识C语言</h1><div class="post-meta"><span class="post-meta-item post-meta-item--createtime"><span class="post-meta-item__icon"><i class="far fa-calendar-plus"></i></span><span class="post-meta-item__info">发表于</span><span class="post-meta-item__value">2022-01-19</span></span><span class="post-meta-item post-meta-item--updatetime"><span class="post-meta-item__icon"><i class="far fa-calendar-check"></i></span><span class="post-meta-item__info">更新于</span><span class="post-meta-item__value">2022-01-22</span></span></div></header><div class="post-body"><p>–本文参考书籍：</p>
<p>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Stephen Prata的《C Primer Plus》</p>
<span id="more"></span>

        <h2 id="前言"   >
          <a href="#前言" class="heading-link"><i class="fas fa-link"></i></a><a href="#前言" class="headerlink" title="前言"></a>前言</h2>
      <p>C 语言是一门抽象的、面向过程的语言，C 语言广泛应用于底层开发，C 语言在计算机体系中占据着不可替代的作用，可以说 C 语言是编程的基础，也就是说，不管你学习任何语言，都应该把 C 语言放在首先要学的位置上。下面这张图形象地说明 C 语言的重要性</p>
<center>
  <img src="https://s4.ax1x.com/2022/01/18/70YL7D.png">
</center>


        <h2 id="什么是C语言"   >
          <a href="#什么是C语言" class="heading-link"><i class="fas fa-link"></i></a><a href="#什么是C语言" class="headerlink" title="什么是C语言"></a>什么是C语言</h2>
      <p>&emsp;&emsp;C 语言是一种通用的、面向过程式的计算机程序设计语言。1972 年，为了移植与开发 UNIX 操作系统，丹尼斯·里奇在贝尔电话实验室设计开发了 C 语言。<br>C 语言是一种广泛使用的计算机语言，它与 Java 编程语言一样普及，二者在现代软件程序员之间都得到广泛使用。<br>当前最新的 C 语言标准为 C18 ，在它之前的 C 语言标准有 C17、C11…C99 等。</p>

        <h2 id="为什么选择C语言"   >
          <a href="#为什么选择C语言" class="heading-link"><i class="fas fa-link"></i></a><a href="#为什么选择C语言" class="headerlink" title="为什么选择C语言"></a>为什么选择C语言</h2>
      <p>&emsp;&emsp;在过去的长时间里，C语言已经成为了最重要、最流行的编程语言之一。它的成长归功于使用过它的人都对其<br>非常满意。在过去的20年间，虽然很多人都从C语言转而使用其他语言(例如：C++，Java等)，但是C语言凭借其自身实力在众多语言中脱颖而出。<br>C语言相较于其他高级语言尤其自己独特的优势，C语言在运行时候其效率是非常高的，并且后来的许多边长语言都是基于C语言来进一步拓展的，故有“C生万物”之说。</p>

        <h3 id="设计特性"   >
          <a href="#设计特性" class="heading-link"><i class="fas fa-link"></i></a><a href="#设计特性" class="headerlink" title="设计特性"></a>设计特性</h3>
      <p>&emsp;&emsp;C语言融合了计算机科学理论和实践的控制特性。C语言的设计理念能让用户能轻松地完成自顶向下的规划、结构化编程和模块化设计。因此用C语言编写的程序更易懂、更可靠。</p>

        <h3 id="高效性"   >
          <a href="#高效性" class="heading-link"><i class="fas fa-link"></i></a><a href="#高效性" class="headerlink" title="高效性"></a>高效性</h3>
      <p>&emsp;&emsp;C语言是一门较高效的编程语言。在设计上，它充分利用了当下计算机的优势，C语言程序相对更紧凑，运行速度更快。C语言具有通常是汇编语言才具有的微调控制能力(<em>汇编语言是为特殊的中央处理器单元设计的一系列内部指令</em>)，可以根据具体情况微调程序以获得最大运行速度或最有效的使用内存。</p>

        <h3 id="可移植性"   >
          <a href="#可移植性" class="heading-link"><i class="fas fa-link"></i></a><a href="#可移植性" class="headerlink" title="可移植性"></a>可移植性</h3>
      <p>&emsp;&emsp;C 语言是一门具有可移植性的语言，这就意味着，对于在一台计算机上编写的 C 语言程序可以在另一台计算机上轻松地运行，从而极大的减少了程序移植的工作量。</p>

        <h3 id="强大而灵活"   >
          <a href="#强大而灵活" class="heading-link"><i class="fas fa-link"></i></a><a href="#强大而灵活" class="headerlink" title="强大而灵活"></a>强大而灵活</h3>
      <p>&emsp;&emsp;C语言功能强大且灵活(计算机领域经常使用这两个词)。</p>
<p>&emsp;&emsp;例如，功能强大的UNIX操作系统，大部分是用C语言编写的；其他语言(如perl，python，BASIC等)的许多编译器和解释器都是使用C语言编写的。因此，在UNIX机上使用FORTRAN时，最终时由C程序生成最后的可执行程序。C程序可以用于解决物理学和工程学的问题，甚至可以制作电影的动画特效。</p>

        <h3 id="面向程序员"   >
          <a href="#面向程序员" class="heading-link"><i class="fas fa-link"></i></a><a href="#面向程序员" class="headerlink" title="面向程序员"></a>面向程序员</h3>
      <p>&emsp;&emsp;C语言是为了满足程序员的需求而设计的，程序员利用C可以访问硬件、操控内存中的位。C语言由丰富的运算符，能让程序员简洁地表达自己的意图。大多数C实现都有一个的大型的库，包含众多的有用的C函数。这些函数用于处理程序员经常需要解决的问题。</p>

        <h2 id="C语言的应用范围"   >
          <a href="#C语言的应用范围" class="heading-link"><i class="fas fa-link"></i></a><a href="#C语言的应用范围" class="headerlink" title="C语言的应用范围"></a>C语言的应用范围</h2>
      <p>&emsp;&emsp;早在20世纪80年代，C语言就已经成为小型计算机（UNI1X系统）使用的主流语言。从那以后C语言的应用范围扩展到微型机（个人计算机）和大型机（庞然大物）。许多软件公司都用语言来开发文字处理程序电子表格编译器和其他产品，因为用语编写的程序紧凑而高效。更重要的是，C程序很方便修师移到新型号的计算机中也没什么问题。<br>无论是软件公司、经验丰富的程序员，还是其他用户，都能从C语言中收益。越来越多的计算机用户已转而求助C语言解决一些安全问题。不一定非得是计算机专家也能使用C语言。<br>20世纪90年代，许多软件公司开始改用C＋＋来开发大型的编程项目。C++在C语言的基础上嫁接了面向对象编程工具。C＋几乎是C的超集，这意味任何C程序差不多就是一个C++程序。学习C语言，也相当于学习了许多C++的知识。</p>
<center>
 <img src = "https://s4.ax1x.com/2022/01/18/7BlmHH.png">
</center>

<center>
 <font face="楷体">C语言的应用范围</font>
</center>
虽然这些年来C++和JAVA非常流行,但是C语言仍是软件业中的核心技能。在最想具备的技能中,C
语言通常位居前十。特别是,C语言已成为嵌入式系统编程的流行语言。也就是说,越来越多的汽车、照
相机、DVD播放机和其他现代化设备的微处理器都用C语言进行编程。除此之外,C语言还从长期被
FORTRAN独占的科学编程领域分得一杯羹。最终,作为开发操作系统的卓越语言,C在 Linux开发中扮演
着极其重要的角色。因此,在进入21世纪的第2个10年中,C语言仍然保持着强劲的势头。
简而言之,C语言是最重要的编程语言之一,将来也是如此。如果你想拿下一份编程的工作,被问到
是否会C语言时,最好回答“是”。

<p>如果您有什么问题或建议可以在下方的评论区评论，我会及时回复的。</p>
<center><font color="red">欢迎关注我的公众号，共同学习，共同提升！</font></center>
<center><font color="red">您可以通过公众号向我留言，也可以通过邮箱（lklong@88.com）联系我</font></center>
<center>
    <img src="https://s4.ax1x.com/2022/01/03/Tb8ZB4.png">
</center>

</div><footer class="post-footer"><div class="post-ending ending"><div class="ending__text">------ 本文结束，感谢您的阅读 ------</div></div><div class="post-copyright copyright"><div class="copyright-author"><span class="copyright-author__name">本文作者: </span><span class="copyright-author__value"><a href="https://kohler19.gitee.io">李恺龙</a></span></div><div class="copyright-link"><span class="copyright-link__name">本文链接: </span><span class="copyright-link__value"><a href="https://kohler19.gitee.io/2022/01/19/%E5%88%9D%E8%AF%86C%E8%AF%AD%E8%A8%80/">https://kohler19.gitee.io/2022/01/19/%E5%88%9D%E8%AF%86C%E8%AF%AD%E8%A8%80/</a></span></div><div class="copyright-notice"><span class="copyright-notice__name">版权声明: </span><span class="copyright-notice__value">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" rel="external nofollow" target="_blank">BY-NC-SA</a> 许可协议。转载请注明出处！</span></div></div><div class="post-tags"><span class="post-tags-item"><span class="post-tags-item__icon"><i class="fas fa-tag"></i></span><a class="post-tags-item__link" href="https://kohler19.gitee.io/tags/C%E8%AF%AD%E8%A8%80/">C语言</a></span></div><nav class="post-paginator paginator"><div class="paginator-prev"><a class="paginator-prev__link" href="/2022/01/19/C-Primer-Plus%EF%BC%88%E7%AC%AC6%E7%89%88%EF%BC%89%E4%B8%AD%E6%96%87%E7%89%88/"><span class="paginator-prev__icon"><i class="fas fa-angle-left"></i></span><span class="paginator-prev__text">C Primer Plus（第6版）中文版</span></a></div><div class="paginator-next"><a class="paginator-next__link" href="/2022/01/05/%E6%80%BB%E7%BB%93%E4%B8%80%E4%B8%8BC%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86%E5%90%A7/"><span class="paginator-prev__text">总结一下C语言基础知识吧</span><span class="paginator-next__icon"><i class="fas fa-angle-right"></i></span></a></div></nav></footer></div></div><div class="comments" id="comments"><div id="valine-container"></div></div></div><div class="sidebar-wrap" id="sidebar-wrap"><aside class="sidebar" id="sidebar"><div class="sidebar-nav"><span class="sidebar-nav-toc current">文章目录</span><span class="sidebar-nav-ov">站点概览</span></div><section class="sidebar-toc"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">
          前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFC%E8%AF%AD%E8%A8%80"><span class="toc-number">2.</span> <span class="toc-text">
          什么是C语言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E9%80%89%E6%8B%A9C%E8%AF%AD%E8%A8%80"><span class="toc-number">3.</span> <span class="toc-text">
          为什么选择C语言</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%BE%E8%AE%A1%E7%89%B9%E6%80%A7"><span class="toc-number">3.1.</span> <span class="toc-text">
          设计特性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%AB%98%E6%95%88%E6%80%A7"><span class="toc-number">3.2.</span> <span class="toc-text">
          高效性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%AF%E7%A7%BB%E6%A4%8D%E6%80%A7"><span class="toc-number">3.3.</span> <span class="toc-text">
          可移植性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%BA%E5%A4%A7%E8%80%8C%E7%81%B5%E6%B4%BB"><span class="toc-number">3.4.</span> <span class="toc-text">
          强大而灵活</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E7%A8%8B%E5%BA%8F%E5%91%98"><span class="toc-number">3.5.</span> <span class="toc-text">
          面向程序员</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#C%E8%AF%AD%E8%A8%80%E7%9A%84%E5%BA%94%E7%94%A8%E8%8C%83%E5%9B%B4"><span class="toc-number">4.</span> <span class="toc-text">
          C语言的应用范围</span></a></li></ol></section><!-- ov = overview--><section class="sidebar-ov hide"><div class="sidebar-ov-author"><div class="sidebar-ov-author__avatar"><img class="sidebar-ov-author__avatar_img" src="https://s4.ax1x.com/2022/01/03/Tb2VW6.png" alt="avatar"></div><p class="sidebar-ov-author__text">格物致知，知行合一</p></div><div class="sidebar-ov-social"><a class="sidebar-ov-social-item" href="https://s4.ax1x.com/2022/01/03/Tb8ZB4.png" target="_blank" rel="noopener" data-popover="微信" data-popover-pos="up"><span class="sidebar-ov-social-item__icon"><i class="fab fa-weixin"></i></span></a><a class="sidebar-ov-social-item" href="mailto:lklong@88.com" target="_blank" rel="noopener" data-popover="social.Email" data-popover-pos="up"><span class="sidebar-ov-social-item__icon">lklong@88.com</span></a></div><div class="sidebar-ov-cc"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" target="_blank" rel="noopener" data-popover="知识共享许可协议" data-popover-pos="up"><img src="/images/cc-by-nc-sa.svg"></a></div></section><div class="sidebar-reading"><div class="sidebar-reading-info"><span class="sidebar-reading-info__text">你已阅读了 </span><span class="sidebar-reading-info__num">0</span><span class="sidebar-reading-info__perc">%</span></div><div class="sidebar-reading-line"></div></div></aside></div><div class="clearfix"></div></div></main><footer class="footer" id="footer"><div class="footer-inner"><div><span>Copyright © 2023</span><span class="footer__icon"><i class="fas fa-heart"></i></span><span>愷龍 All Rights Reserved</span></div><div><span>由 <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a> 强力驱动</span><span> v5.4.0</span><span class="footer__devider">|</span><span>主题 - <a href="https://github.com/liuyib/hexo-theme-stun/" title="Stun" target="_blank" rel="noopener">Stun</a></span><span> v2.6.2</span></div></div></footer><div class="loading-bar" id="loading-bar"><div class="loading-bar__progress"></div></div><div class="back2top" id="back2top"><span class="back2top__icon"><i class="fas fa-rocket"></i></span></div></div><div class="search-mask"></div><div class="search-popup"><span class="search-close"></span><div class="search-input"><input placeholder="搜索文章（支持多关键词，请用空格分隔）"></div><div class="search-results"></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@v3.4.1/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.ui.min.js"></script><script>function initSearch() {
  var isXML = true;
  var search_path = 'search.xml';

  if (!search_path) {
    search_path = 'search.xml';
  } else if (/json$/i.test(search_path)) {
    isXML = false;
  }

  var path = '/' + search_path;
  $.ajax({
    url: path,
    dataType: isXML ? 'xml' : 'json',
    async: true,
    success: function (res) {
      var datas = isXML ? $('entry', res).map(function () {
        // 将 XML 转为 JSON
        return {
          title: $('title', this).text(),
          content: $('content', this).text(),
          url: $('url', this).text()
        };
      }).get() : res;
      var $input = $('.search-input input');
      var $result = $('.search-results');
      // 搜索对象（标题、内容）的权重，影响显示顺序
      var WEIGHT = { title: 100, content: 1 };
      var searchPost = function () {
        var searchText = $input.val().toLowerCase().trim();
        // 根据空白字符分隔关键字
        var keywords = searchText.split(/[\s]+/);
        // 搜索结果
        var matchPosts = [];

        // 有多个关键字时，将原文字整个保存下来
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        // 防止未输入字符时搜索
        if (searchText.length > 0) {
          datas.forEach(function (data) {
            var isMatch  = false;
            // 没有标题的文章使用预设的 i18n 变量代替
            var title = (data.title && data.title.trim()) || '[ 文章无标题 ]';
            var titleLower = title && title.toLowerCase();
            // 删除 HTML 标签 和 所有空白字符
            var content = data.content && data.content.replace(/<[^>]+>/g, '');
            var contentLower = content && content.toLowerCase();
            // 删除重复的 /
            var postURL = data.url && decodeURI(data.url).replace(/\/{2,}/g, '/');
            // 标题中匹配到的关键词
            var titleHitSlice = [];
            // 内容中匹配到的关键词
            var contentHitSlice = [];

            keywords.forEach(function (keyword) {
              /**
              * 获取匹配的关键词的索引
              * @param {String} keyword 要匹配的关键字
              * @param {String} text 原文字
              * @param {Boolean} caseSensitive 是否区分大小写
              * @param {Number} weight 匹配对象的权重。权重大的优先显示
              * @return {Array}
              */
              function getIndexByword (word, text, caseSensitive, weight) {
                if (!word || !text) {
                  return [];
                };

                var startIndex = 0; // 每次匹配的开始索引
                var index = -1;     // 匹配到的索引值
                var result = [];    // 匹配结果

                if (!caseSensitive) {
                  word = word.toLowerCase();
                  text = text.toLowerCase();
                }

                while((index = text.indexOf(word, startIndex)) !== -1) {
                  var hasMatch = false;
                  // 索引位置相同的关键词，保留长度较长的
                  titleHitSlice.forEach(function (hit) {
                    if (hit.index === index && hit.word.length < word.length) {
                      hit.word = word;
                      hasMatch = true;
                    }
                  });
                  startIndex = index + word.length;
                  !hasMatch && result.push({ index: index, word: word, weight: weight });
                }
                return result;
              }
              titleHitSlice = titleHitSlice.concat(getIndexByword(keyword, titleLower, false, WEIGHT.title));
              contentHitSlice = contentHitSlice.concat(getIndexByword(keyword, contentLower, false, WEIGHT.content));
            });

            var hitTitle = titleHitSlice.length;
            var hitContent = contentHitSlice.length;

            if (hitTitle > 0 || hitContent > 0) {
              isMatch = true;
            }
            if (isMatch) {
              ;[titleHitSlice, contentHitSlice].forEach(function (hit) {
                // 按照匹配文字的索引的递增顺序排序
                hit.sort(function (left, right) {
                  return left.index - right.index;
                });
              });
              /**
              * 给文本中匹配到的关键词添加标记，从而进行高亮显示
              * @param {String} text 原文本
              * @param {Array} hitSlice 匹配项的索引信息
              * @param {Number} start 开始索引
              * @param {Number} end 结束索引
              * @return {String}
              */
              function highlightKeyword (text, hitSlice, start, end) {
                if (!text || !hitSlice || !hitSlice.length) {
                  return;
                }

                var result = '';
                var startIndex = start;
                var endIndex = end;
                hitSlice.forEach(function (hit) {
                  if (hit.index < startIndex) {
                    return;
                  }

                  var hitWordEnd = hit.index + hit.word.length;
                  result += text.slice(startIndex, hit.index);
                  result += '<b>' + text.slice(hit.index, hitWordEnd) + '</b>';
                  startIndex = hitWordEnd;
                });
                result += text.slice(startIndex, endIndex);
                return result;
              }

              var postData = {};
              // 文章总的搜索权重
              var postWeight = titleHitSlice.length * WEIGHT.title + contentHitSlice.length * WEIGHT.content;
              // 标记匹配关键词后的标题
              var postTitle = highlightKeyword(title, titleHitSlice, 0, title.length) || title;
              // 标记匹配关键词后的内容
              var postContent;
              // 显示内容的长度
              var SHOW_WORD_LENGTH = 200;
              // 命中关键词前的字符显示长度
              var SHOW_WORD_FRONT_LENGTH = 20;
              var SHOW_WORD_END_LENGTH = SHOW_WORD_LENGTH - SHOW_WORD_FRONT_LENGTH;

              // 截取匹配的第一个字符，前后共 200 个字符来显示
              if (contentHitSlice.length > 0) {
                var firstIndex = contentHitSlice[0].index;
                var start = firstIndex > SHOW_WORD_FRONT_LENGTH ? firstIndex - SHOW_WORD_FRONT_LENGTH : 0;
                var end = firstIndex + SHOW_WORD_END_LENGTH;
                postContent = highlightKeyword(content, contentHitSlice, start, end);
              } else { // 未匹配到内容，直接截取前 200 个字符来显示
                postContent = content.slice(0, SHOW_WORD_LENGTH);
              }
              postData.title = postTitle;
              postData.content = postContent;
              postData.url = postURL;
              postData.weight = postWeight;
              matchPosts.push(postData);
            }
          });
        }

        var resultInnerHtml = '';
        if (matchPosts.length) {
          // 按权重递增的顺序排序，使权重大的优先显示
          matchPosts.sort(function (left, right) {
            return right.weight - left.weight;
          });
          resultInnerHtml += '<ul>';
          matchPosts.forEach(function (post) {
            resultInnerHtml += '<li><a class="search-results-title" href="' + post.url + '">';
            resultInnerHtml += post.title;
            resultInnerHtml += '</a><div class="search-results-content">';
            resultInnerHtml += post.content;
            resultInnerHtml += '</div></li>';
          });
          resultInnerHtml += '</ul>';
        } else {
          resultInnerHtml += '<div class="search-results-none"><i class="far fa-meh"></i></div>';
        }
        $result.html(resultInnerHtml);
      };
      $input.on('input', searchPost);
      $input.on('keyup', function (e) {
        if (e.keyCode === Stun.utils.codeToKeyCode('Enter')) {
          searchPost();
        }
      });
    }
  });
}

function closeSearch () {
  $('body').css({ overflow: 'auto' });
  $('.search-popup').css({ display: 'none' });
  $('.search-mask').css({ display: 'none' });
}

window.addEventListener('DOMContentLoaded', function () {
  Stun.utils.pjaxReloadLocalSearch = function () {
    $('.header-nav-search').on('click', function (e) {
      e.stopPropagation();
      $('body').css('overflow', 'hidden');
      $('.search-popup')
        .velocity('stop')
        .velocity('transition.expandIn', {
          duration: 300,
          complete: function () {
            $('.search-popup input').focus();
          }
        });
      $('.search-mask')
        .velocity('stop')
        .velocity('transition.fadeIn', {
          duration: 300
        });

      initSearch();
    });
    $('.search-mask, .search-close').on('click', function () {
      closeSearch();
    });
    $(document).on('keydown', function (e) {
      // Escape <=> 27
      if (e.keyCode === Stun.utils.codeToKeyCode('Escape')) {
        closeSearch();
      }
    });
  };

  Stun.utils.pjaxReloadLocalSearch();
}, false);

function safeOpenUrl(url) {
  var newTab = window.open();
  newTab.opener = null;
  newTab.location = url;
}

function extSearch(engine) {
  var engines = {
    google: 'https://www.google.com/search?q=',
    bing: 'https://cn.bing.com/search?q=',
    baidu: 'https://www.baidu.com/s?ie=UTF-8&wd=',
  };
  var host = window.location.host;
  var query = $('.search-input input').val().toLowerCase().trim();
  var uri = engines[engine] + query + ' site:' + host;

  if (query) {
    safeOpenUrl(uri);
  } else {
    Stun.utils.popAlert('warning', '请输入字符');
  }
}

var assistSearchList = window.CONFIG.assistSearch;

if (Array.isArray(assistSearchList)) {
  assistSearchList.forEach(function (name) {
    document.querySelector('.search-btns-item--' + name).addEventListener('click', function () {
      extSearch(name);
    }, false);
  });
}</script><script src="https://cdn.jsdelivr.net/npm/leancloud-storage@latest/dist/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js"></script><script>function loadValine () {
  var GUEST_INFO = ['nick', 'mail', 'link'];
  var guest_info = 'nick,mail,link';

  guest_info = guest_info.split(',').filter(function(item) {
    return GUEST_INFO.indexOf(item) > -1;
  });
  new Valine({
    el: '#valine-container',
    appId: 'lxsmJYFBR3TcsTpKPFWSN0HX-gzGzoHsz',
    appKey: 'lW6taHRzBHFtJeWSSzXXMAxH',
    notify: true,
    verify: true,
    placeholder: 'Just go go',
    avatar: 'mp',
    meta: guest_info,
    pageSize: '10' || 10,
    visitor: false,
    recordIP: false,
    lang: '' || 'zh-cn',
    path: window.location.pathname
  });
}

if (false) {
  loadValine();
} else {
  window.addEventListener('DOMContentLoaded', loadValine, false);
}</script><script src="/js/utils.js?v=2.6.2"></script><script src="/js/stun-boot.js?v=2.6.2"></script><script src="/js/scroll.js?v=2.6.2"></script><script src="/js/header.js?v=2.6.2"></script><script src="/js/sidebar.js?v=2.6.2"></script><script type="application/json" src="/search.xml"></script></body></html>